<?php
/**
 * 定义f:select控件
 * 
 * 支持的参数有：
 * - values
 * - labels
 * - selected.values
 * - selected.list
 * - options
 *
 * @package if
 * @subpackage module.ui
 * @since 1.1.0
 */
class UIFormSelect extends UIFormElement {
	protected $tpl = "form_select";
	protected $groupValue = true;
	
	function render() {
		$this->addReserveAttrs(array( "values", "labels", "selected", "options" ));
		
		//是否有预定义好的options
		$values = $this->attr("values");
		$labels = array();
		$options = array();
		if (!is_array($values)) {
			$options = $this->attr("options");
			if (is_array($options)) {
				$values = array_keys($options);
				$labels = array_values($options);
			}
		}
		$labels2 = $this->attr("labels");
		if (is_array($labels2)) {
			$labels = $labels2;
		}
		
		//name
		$name = $this->attr("name");
		if ($this->attr("multiple")) {
			$name = $this->attr("name") . "[]";
			$this->setAttr("name", $name);
		}
		
		$options = array();
		if (is_array($values)) {
			foreach ($values as $key => $value) {
				$options[$key] = "<option value=\"" . $this->escape(strval($value)) . "\"";
				$selectValues = $this->attr("selected.values");
				$selectedList = $this->attr("selected.list");
				if ((is_array($selectValues) && in_array($value, $selectValues)) || ($selectedList && if_in_array($value, $selectedList))) {
					$options[$key] .= " selected=\"selected\"";
				}
				elseif ($this->can("redisplay") && $name) {
					$values = $this->request($name, true);
					if ((is_array($values) && in_array($value, $values)) || ($values == $value)) {
						$options[$key] .= " selected=\"selected\"";
					}
				}
				$options[$key] .= ">";
				if (isset($labels[$key])) {
					$options[$key] .= $labels[$key];
				}
				$options[$key] .= "</option>";
			}
		}
		$this->addTplVar("options", $options ? implode("\n", $options) : "");
		
		$this->addReserveAttrs("value");
		if ($this->attr("multiple")) {
			$this->setAttr("multiple", "multiple");
		}
		return parent::render();
	}
}

?>